//
//  YLLLoginViewController.swift
//  YLLSina
//
//  Created by 于玲玲 on 16/7/30.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD//这个是什么 干什么的


class YLLLoginViewController: UIViewController ,UIWebViewDelegate{

    let webView = UIWebView()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
     
        setupNav()
        
    
        let url = "https://api.weibo.com/oauth2/authorize?client_id=766883286&redirect_uri=http://www.baidu.com&language=en"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(request)
        
        webView.delegate = self
        
    }
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dissmiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "auto")
    }
    
    @objc private func dissmiss(){
        
        dismissViewControllerAnimated(false) { ()-> Void in
            
        }
        
    }
    
    @objc private func auto(){
        //这句哪来的
        let js = "document.getElementById('userId').value = '13404871584';document.getElementById('passwd').value = '764376975'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension YLLLoginViewController{
    //不懂
    func webView(webView: UIWebView,shouldStartLoadWithRequest request: NSURLRequest,navigationType:
        UIWebViewNavigationType)->Bool{
        
        if let urlString = request.URL?.absoluteString {
            if urlString.hasPrefix(RedrectURL){
                printLog(urlString)
//                不懂
                if let code = request.URL?.query{
                    
                    let subStr = code.substringFromIndex("code=".endIndex)
                    
                    printLog(subStr)
                    
                    YLLLoginViewModel.shareInstance.loadToken(subStr, success: {
                        printLog("最终的回调")
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeViewController, object: self)
                        
                        self.dissmiss()
                        
                        }, failed: { (messgae) in
                            SVProgressHUD.showErrorWithStatus(messgae)
                    })
                    
                }
            }
            
            
        }
        return true
    }
    
    
}

extension YLLLoginViewController{
    
    
}
extension YLLLoginViewController{
    
}

